package com.meritit.product.portal;

import com.meritit.product.spi.ChannelURLFactoryImpl;
import com.meritit.product.spi.PortletWindowContextImpl;
import com.sun.portal.container.ChannelMode;
import com.sun.portal.container.ChannelState;
import com.sun.portal.container.ChannelURLFactory;
import com.sun.portal.container.Container;
import com.sun.portal.container.ContainerFactory;
import com.sun.portal.container.ContainerType;
import com.sun.portal.container.EntityID;
import com.sun.portal.container.GetMarkupRequest;
import com.sun.portal.container.GetMarkupResponse;
import com.sun.portal.container.PortletID;
import com.sun.portal.container.PortletWindowContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class PortalServer extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Container container = ContainerFactory.getContainer(ContainerType.PORTLET_CONTAINER);
        String pid = req.getParameter("portletID");
        String action = req.getParameter("action");
        action = action == null || "".equals(action) ? "view" : action;
        PortletID portletID = new PortletID(pid.split("\\.")[0], pid.split("\\.")[1]);
        EntityID portletEntityid = new EntityID(portletID);
        ChannelState channelState = ChannelState.NORMAL;
        ChannelMode channelMode = new ChannelMode(action);
        PortletWindowContext portletWindowContext = new PortletWindowContextImpl();
        portletWindowContext.init(req);
        ChannelURLFactory channelURLFactory = new ChannelURLFactoryImpl();

        GetMarkupRequest request = container.createGetMarkUpRequest(req, portletEntityid, channelState, channelMode, portletWindowContext, channelURLFactory);
        GetMarkupResponse response = container.createGetMarkUpResponse(resp);

        try {
            container.getMarkup(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }

        req.setAttribute("title", response.getTitle());
        req.setAttribute("content", response.getMarkup());

        req.getRequestDispatcher("/portlet.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
